<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * 后台管理控制器
 * 
 * @author <judasnow@gmail.com>
 */
//便于在非搜索结果的情况下
//分页显示
define( 'INFINITY' , PHP_INT_MAX );

class Admin extends CI_Controller{
	 
	public function __construct(){
		parent::__construct();
		$this->load->database();
		$this->load->helper('url');
		//除了 login 以及 do_login 
		//这两个 uri 之外，均需要登录之后才能访问 so
		$uri = $this->uri->segment_array();
		if( !empty( $uri[2] ) && $uri[2] != 'login' && $uri[2] != 'dologin' ){
                        if( !$this->is_login() ){
                                $this->admin = '';
		 		header( 'Location: /admin' );
		 		exit;		
                        }else{
                                $this->admin = $this->session->userdata( 'admin' );
                        }
		}
	}
	//判断 admin 是不是已经登录 
	private function is_login(){
		$this->admin = $this->session->userdata( 'admin' );
		return empty( $this->admin ) ? FALSE : TRUE; 
	}
	public function login(){
	 	if( $this->is_login() ){
			header( 'Location: /admin' );
			exit;		
		}
		$response_info = $this->session->flashdata( 'response_info' );
		$this->load->view( 'admin/template_page' ,
			array( 'mod'=>'login' , 'response_info'=>$response_info ) );
        }
        //在需要特定权限的操作之前 检查
        //当前管理员是否有相应的权限
        private function check_priv( $needs_priv = 'SUPER' ){
                $admin = $this->session->userdata( 'admin' );
                return $admin['priv'] == $needs_priv ? TRUE : FALSE; 
        }
	//管理员登陆
	public function dologin(){
	/*{{{*/
	        if( $this->is_login() ){
			header( 'Location: /admin' );
			exit;		
		}
		$admin = $this->input->post( 'admin' , TRUE );
		$password = $this->input->post( 'password' , TRUE );
		//登录操作
		$this->db->where( array( 'admin'=>$admin , 'password'=>md5( $password ) ) );
		$res = $this->db->get( 'admin' );
		if( $res->num_rows() == 1 ){
			//有且只有一条记录 
			//登录成功
			$row = $res->result_array();
			$this->session->set_userdata( 'admin' , $row[0] );
			//更新数据库中的登录信息
			$last_login_ipadd = $_SERVER['REMOTE_ADDR'];
			$last_login_time = date( 'Y-m-d H:i:s' , $_SERVER['REQUEST_TIME'] );
			$this->load->model( 'admin_model' , '' , TRUE );
			$this->admin_model->update( 
				array( 'last_login_ipadd'=>$last_login_ipadd , 'last_login_time'=>$last_login_time ) ,
				array( 'admin'=>$admin ) 
			);
			//跳转到首页
			header( 'Location: /admin' );
		        exit;
		}else{
			//保存错误信息
			$this->session->set_flashdata( 'response_info' ,
				array( 'type'=>'error' , 'info'=>'用户名或密码错误' ) );
			//登录失败
			header( 'Location: /admin/login' );
			exit;
		}
	}/*}}}*/
	//退出管理员登录
	public function dologout(){
	/*{{{*/
		$this->session->unset_userdata( 'admin' );
		header( 'Location: /admin/login' );
		exit;
	}/*}}}*/
	public function index(){
	/*{{{*/
		if( !$this->is_login() ){
			header( 'Location: /admin/login' );
			exit;		
		}
		//显示主管理页面
		//默认是服务管理
		$this->load->view( 'admin/template_page' , 
			array( 'mod'=>'index' , 'nav_active'=>'' , 'sub_active'=>'' , 'admin'=>$this->admin ) );
	}/*}}}*/

//服务管理
//需要 SUPER 权限
/*{{{*/
        function product_class(){
		try{
		$action = $this->uri->segment( 3 );
		switch( $action ){
			case 'show':
				$this->show_product_class();
				break;	
			case 'add':
				$this->add_new_product_class();
				break;
			case 'do_add':
				$this->do_add_new_product_class();
				break;
			case 'detail':
				$this->product_class_detail();
				break;
			default:
				$this->show_product_class();
				break;
		} 
		}catch( Exception $e ){
			 log_message( 'error' , $e->getMessage() );
			 log_message( 'error' , $e->getTraceAsString() );
			 handle_exception( $e );
		}
	}	 
	/**
	 * 服务管理 也就是商品分类的管理
	 */
	public function product_class_admin(){
	/*{{{*/
		$this->load->view( 'admin/template_page' , 
			array( 'mod'=>'index' , 'nav_active'=>'product_class_admin' , 'sub_active'=>'' , 'admin'=>$this->admin ) );
	}/*}}}*/

	//显示已有的服务
	private function show_product_class(){
	/*{{{*/
		$this->load->model( 'product_class_model' , '' , TRUE );
		$product_classes = $this->product_class_model->find_all();

		$this->load->view( 'admin/template_page' , 
			array( 'mod'=>'product_class_show' , 'nav_active'=>'product_class_admin' , 'sub_active'=>'show' ,
			 	'product_classes'=>$product_classes , 'admin'=>$this->admin ) );
	}/*}}}*/
	
	//改变商品在首页的显示顺序
	public function ajax_do_new_sort_list_product_class(){
        /*{{{*/
                if( !$this->check_priv( 'SUPER' ) ){
                        echo json_encode( array( 'check_priv'=>'FALSE' , 'res'=>'FALSE' ) );
                        return;
                }
		$this->load->model( 'product_class_model' , '' , TRUE );
		//获得用户发送来的服务顺序信息
		//因为只有数字信息 可以用检查输入
                foreach( $_POST as $order=>$product_class_name ){
                        if( !is_integer( $order ) ){
                                continue;
                        }
                        try{
                                //根据新的 sort_list 更新数据库
                                $this->product_class_model->update(
                                        //避免出现 0			 
                                        array( 'order'=>$order+1 ) ,
                                        array( 'product_class_name'=>$product_class_name ) );
                        }catch( Exception $e ){
                                //更新失败
                                echo '{"res":"FALSE"}';
                        }
                }
                echo '{"res":"TRUE"}';
        }/*}}}*/

        //获得 dir map
        //$path 为相对地址
        private function get_dir_map( $path ){
                $this->load->helper('file');
                return get_dir_file_info( $path );
        }

        //改变首页的可见性
        public function ajax_toggle_product_class_show(){
                if( !$this->check_priv( 'SUPER' ) ){
                        echo json_encode( array( 'check_priv'=>'FALSE' , 'res'=>'FALSE' ) );
                        return;
                }
                $product_class_name = $this->input->post( 'product_class_name' , TRUE );
                $show = $this->input->post( 'show' , TRUE );
                $this->load->model( 'product_class_model' , '' , TRUE );
                try{
                        if( !is_numeric( $show ) || !empty( $product_class_name ) ){
                                //throw new Exception( '改变商品分类在首页的可见性时传入的参数非法' );
                        }
                        $this->product_class_model->update( array( 'show'=>$show ) , array( 'product_class_name'=>$product_class_name ) );
                        echo '{"res":"TRUE"}';
                }catch( Exception $e ){
                        echo '{"res":"FALSE"}';
                        handle_exception( $e );
                }
        }

        //异步获取目录
        public function ajax_get_dir_map(){
                $dir_path = $this->input->get( 'dir_path' , TRUE );
                echo json_encode( $this->get_dir_map( $dir_path ) );
        }

        public function ajax_get_file_content(){
                $this->load->helper('file');
                $file_path = $this->input->get( 'file_path' , TRUE );
                $file_content = @read_file( $file_path );
                if( !$file_content ){
                        echo '';
                }else{
                        echo $file_content;
                }
        }

        public function ajax_do_update_file_content(){
                if( !$this->check_priv( 'SUPER' ) ){
                        echo json_encode( array( 'check_priv'=>'FALSE' , 'res'=>'FALSE' ) );
                        return;
                }
                $this->load->helper('file');
                $file_content = $this->input->post( 'file_content' );
                $this_file_path = $this->input->post( 'this_file_path' , TRUE );
                if( @write_file( $this_file_path , $file_content ) ){
                        echo '{"res":"TRUE"}';
                }else{
                        echo '{"res":"FALSE"}';
                }	
        }

        public function ajax_do_add_new_file(){
                if( !$this->check_priv( 'SUPER' ) ){
                        echo json_encode( array( 'check_priv'=>'FALSE' , 'res'=>'FALSE' ) );
                        return;
                }
                $name = $this->input->post( 'name' , TRUE );
                //不需要进行转意
                $content = $this->input->post( 'content' );
                $file_path = $this->input->post( 'file_path' , TRUE );
                $this->load->helper('file');
                //尝试写入文件
                if( write_file( "$file_path/$name"  , $content ) ){
                        echo '{"res":"TRUE"}';
                }else{
                        echo '{"res":"FALSE"}';
                }
        }

        public function ajax_do_del_file(){
                if( !$this->check_priv( 'SUPER' ) ){
                        echo json_encode( array( 'check_priv'=>'FALSE' , 'res'=>'FALSE' ) );
                        return;
                }
                $file_path = $this->input->post( 'file_path' , TRUE );
                $this->load->helper('file');
                //尝试写入文件
                if( delete_files( $file_path ) ){
                        echo '{"res":"TRUE"}';
                }else{
                        echo '{"res":"FALSE"}';
                }
        }

        //显示服务的详细信息
        private function product_class_detail(){
                /*{{{*/
                $product_class_name = $this->input->get( 'product_class_name' , TRUE );
		 if( empty( $product_class_name ) ){
			 header( 'Location: /admin/product_class/show/' );
			 exit;
		 }
		 //读取相关的信息 
		 //重要的是读取文件列表
		 $this->load->model( 'product_class_model' , '' , TRUE );
		 $product_class = $this->product_class_model->find( array( 'product_class_name'=>$product_class_name ) );
		 if( empty( $product_class ) ){
			 header( 'Location: /admin/product_class/show/' );
			 exit;
		 }
		 $product_class_name = $product_class['product_class_name'];
		 //顶级目录
		 $top_dir_map = $this->get_dir_map( APPPATH . "/views/mod/base_index_product_class_infos/$product_class_name/" );
		 $this->load->view( 'admin/template_page' , 
			 array( 'mod'=>'product_class_detail' , 'nav_active'=>'product_class_admin' , 'sub_active'=>'detail' , 
				 'detail_describe'=>"{$product_class['product_class_name_cn']}编辑页面" , 
				 'product_class'=>$product_class , 'top_dir_map'=>$top_dir_map , 'admin'=>$this->admin ) );
	}/*}}}*/
	
	//添加一个新的服务
	private function add_new_product_class(){
	/*{{{*/
		$error = $this->session->flashdata( 'error' );
		$this->load->view( 'admin/template_page' , 
			array( 'mod'=>'add_new_product_class' , 'nav_active'=>'product_class_admin' , 'sub_active'=>'add' , 'error'=>$error , 'admin'=>$this->admin) );
	}/*}}}*/

	//添加新的服务类别
	private function do_add_new_product_class(){
	/*{{{*/
                if( !$this->check_priv( 'SUPER' ) ){
                        $this->session->set_flashdata( 'error' , array( 'info'=>'您的权限无法进行此项操作' ) );
                        header( 'Location: /admin/product_class/add/' );
                        exit;
                }
		$product_class_name = $this->input->post( 'product_class_name' , TRUE );
		$product_class_name_cn = $this->input->post( 'product_class_name_cn' , TRUE );
		$product_class_describe = $this->input->post( 'product_class_describe' , TRUE );
		//判断新添加服务的有效性
		if( empty( $product_class_name ) || empty( $product_class_name_cn ) ){
			$this->session->set_flashdata( 'error' , array( 'info'=>'请检查服务名称，两个都不能为空' ) );
			header( 'Location: /admin/product_class/add/' );
			exit;
		}
		//数据库中保存的名字 必须由字母组成
		if( !preg_match( "/^[A-Za-z.]+$/ " , $product_class_name ) ){
			$this->session->set_flashdata( 'error' , array( 'info'=>'用于数据库中的"服务名称”必须为字母' ) );
			header( 'Location: /admin/product_class/add/' );
			exit;
		}
		$this->load->library( 'product_class' );
		try{
			$this->product_class->add_new( array( 'product_class_name'=>$product_class_name , 'product_class_name_cn'=>$product_class_name_cn ) , $product_class_describe );
			header( 'Location: /admin/product_class/show/' );
			exit;
		}catch( RuntimeException $e ){
			$this->session->set_flashdata( 'error' , array( 'info'=>$e->getMessage() ) );
			header( 'Location: /admin/product_class/add/' );
			exit;
		}catch( Exception $e ){
			handle_exception( $e );
		}
	}/*}}}*/

	//从数据库中删除一个服务
	public function ajax_do_delete_product_class(){
	/*{{{*/
                if( !$this->check_priv( 'SUPER' ) ){
                        echo json_encode( array( 'check_priv'=>'FALSE' , 'res'=>'FALSE' ) );
                        return;
                }
		$product_class_name = $this->input->post( 'product_class_name' , TRUE );
		$this->load->library( 'product_class' );
		try{
			$this->product_class->del( array( 'product_class_name'=>$product_class_name ) );
			echo '{"res":"TRUE"}';
		}catch( Exception $e ){
			echo '{"res":"FALSE"}';
			handle_exception( $e );
		}
	}/*}}}*/
/*}}}*/

//交易管理 
/*{{{*/
	public function order(){
		try{
		$action = $this->uri->segment( 3 );
		switch( $action ){
			case 'today':
				$this->order_today();
				break;	
			case 'show':
				$this->show_orders();
				break;
			case 'product_stat':
				$this->show_product_stat();
				break;
			case 'search':
				$this->order_search();
				break;
			case 'do_search':
				$this->do_order_search();
				break;
			case 'refesh_order_stat':
				$this->refesh_order_stat();
				break;
			default:
				$this->order_today();
				break;
		} 
		}catch( Exception $e ){
			 log_message( 'error' , $e->getMessage() );
			 log_message( 'error' , $e->getTraceAsString() );
			 handle_exception( $e );
		}
	}

	//显示当天的订单的汇总信息
	private function order_today(){
	/*{{{*/
		 //获取本日订单的总数
		 $this->load->model( 'order_model' , '' , TRUE );
		 $today_order = $this->order_model->get_today_order();
		 $this->load->view( 'admin/template_page' , 
			array( 'mod'=>'order_today' , 'nav_active'=>'order_admin' , 'sub_active'=>'today' , 'today_order'=>$today_order , 'admin'=>$this->admin ) );
	}/*}}}*/

	//刷新商品的销售信息
        private function refesh_order_stat(){
/*{{{*/
		 $this->load->model( 'product_at_spec_class_model' , '' , TRUE );
		 $all_product_in_spec_class_infos = $this->product_at_spec_class_model->find_all();
		 //更新全部的 销售信息
		 $this->load->model( 'order_model' , '' , TRUE );
		 $sum_of_item = count( $all_product_in_spec_class_infos );
		 ob_start(); 
		 ob_implicit_flush(1);
		 echo '
<html>
<head>
<script src="/js/libs/jquery-1.6.2.min.js"></script>
<script src="/js/libs/jquery-ui/js/jquery-ui-1.8.16.custom.min.js"></script>
<link rel="stylesheet" href="/js/libs/jquery-ui/css/flick/jquery-ui-1.8.17.custom.css" type="text/css" media="screen, projection">
<style>
.proc{
	display:none;
}
</style>
</head>
<body>
<div id="progressbar"></div>
<script type="text/javascript">
var process_el = $( "#progressbar" );
var i = 1;
var interval_id = setInterval( function(){
	var proc = $( ".proc" ).last().text();
	proc = parseInt( proc );
	if( proc == 100 ){
		 clearInterval( interval_id );
		 //更新完成 跳转到 order/product_stat 页面
		 window.location.href="/admin/order/product_stat/";
	}
	process_el.progressbar({
		 value: proc
	});
} , 100 );	 

</script>
</body>
</html>			 
';
		 foreach( $all_product_in_spec_class_infos as $index=>$product_in_spac_class_info ){
			 $order_count = $this->order_model->get_product_order_stat( $product_in_spac_class_info['product_id'] , $product_in_spac_class_info['product_class_id'] );
			 $this->product_at_spec_class_model->update(
				 array( 'sales'=>$order_count['sales'] , 'sales_today'=>$order_count['sales_today'] ) ,
				 array( 'product_id'=>$product_in_spac_class_info['product_id'] , 'product_class_id'=>$product_in_spac_class_info['product_class_id'] )
			 );
			 echo str_repeat( " " , 4096 ); 
			 //为了能输出 100% 总数要减一
			 echo '<span class="proc" >' . ceil(( $index / ($sum_of_item-1) ) * 100 ) . '</span>';
			 ob_flush();
			 flush();
		 }
	}/*}}}*/

	//显示商品列表以及历史购买的统计信息 当日/历史
	private function show_product_stat(){
	/*{{{*/
		 //@todo 似乎有注入漏洞
		 $order_by = $this->uri->segment( 4 );
		 $order = $this->uri->segment( 5 );

		 $this->load->library('pagination');
		 $this->config->load('pagination');

		 $config = $this->config->item( 'pagination' );
		 $config['base_url'] = "/admin/order/product_stat/?";	 
		 $offset = $this->input->get( 'pager' , TRUE );	
		 $per_page = empty( $offset ) ? INFINITY : $config['per_page'];

		 $this->load->model( 'product_at_spec_class_model' , '' , TRUE );
		 $all_product_in_spec_class_infos = $this->product_at_spec_class_model->find_all();
		 
		 $total_rows = count( $all_product_in_spec_class_infos );
		 $config['total_rows'] = $total_rows;
		 $this->pagination->initialize( $config );
		 if( empty( $offset ) ){
			$offset = 0;
		 }
		 //商品原始信息 其实就是 product_at_spec_class 中的元素
		 //这下加上了 class_name 等信息
		 $product_stat_infos = $this->product_at_spec_class_model->find_all_with_spec_class_info(
			'' ,
			array( 'title'=>$order_by , 'order'=>$order ) ,
			$config['per_page'] , 
			$offset 
		 );
		 $pager_links = $this->pagination->create_links();
		 $this->load->view( 'admin/template_page' , 
			 array( 'mod'=>'show_product_stat' , 'nav_active'=>'order_admin' , 'sub_active'=>'product_stat' ,
				  'product_stat_infos'=>$product_stat_infos , 'pager_links'=>$pager_links , 'admin'=>$this->admin ) );
	}/*}}}*/

	//查看所有的订单
	private function show_orders(){
	/*{{{*/		
		$this->load->library('pagination');
		$this->config->load('pagination');
		$this->load->model( 'order_model' , '' , TRUE );
		//获取需要显示订单的具体信息
		//在 uri 4 中
		$cond = $this->uri->segment( 4 );
		if( $cond != 'search' ){
			$this->session->unset_userdata( 'search_sql' );
                }            
		$config = $this->config->item( 'pagination' );
		$config['base_url'] = "/admin/order/show/$cond?";	 
		$offset = $this->input->get( 'pager' , TRUE );
		$search_sql = $this->session->userdata( 'search_sql' );
		if( !empty( $search_sql) ){
			//问题就处在这里 如果在分页显示查询结果时
			//如何确定总的结果个数
			$config['total_rows'] = $this->session->userdata( 'count_search_result' );
			$orders = $this->order_model->find_all( 
			        '' ,
				array( 'title'=>'order_id' , 'order'=>'DESC' ) ,
				$config['per_page'] , 
				$offset ,
				$search_sql
			);
                }else{
                        if( $cond == 'today' ){
                                $today_order = $this->order_model->get_today_order();
                                $orders = $today_order['today_order'];
                                $config['total_rows'] = count( $orders );
                        }else{
			        $config['total_rows'] = $this->db->count_all( 'order' );
			        $orders = $this->order_model->find_all(
			        	'' ,
			        	array( 'title'=>'order_id' , 'order'=>'DESC' ) ,
			        	$config['per_page'] , 
			        	$offset
                                );
                        }
		}
		$this->pagination->initialize( $config );
		if( empty( $offset ) ){
			$offset = 0;
		}
		$pager_links = $this->pagination->create_links();
	 
		$this->load->view( 'admin/template_page' , 
			array( 'mod'=>'order_show' , 'nav_active'=>'order_admin' , 'sub_active'=>'show' , 'orders'=>$orders , 'pager_links'=>$pager_links ,
			 'item_count'=>$config['total_rows'] , 'admin'=>$this->admin ) ); 
	}/*}}}*/

	private function order_search(){	 
	/*{{{*/
		 $this->load->view( 'admin/template_page' , 
			array( 'mod'=>'order_search' , 'nav_active'=>'order_admin' , 'sub_active'=>'search' , 'admin'=>$this->admin ) );
	}/*}}}*/

	public function do_order_search(){
 	/*{{{*/
		 //获取订单时间范围
		 $order_time_from = $this->input->post( 'order_time_from' , TRUE );
		 $order_time_to = $this->input->post( 'order_time_to' , TRUE );
		 
		 //获取商品相关的关键字
		 $product_cond = $this->input->post( 'product_cond' , TRUE );
		 $product_cond_value = $this->input->post( 'product_cond_value' , TRUE );
		 $product_price_from = $this->input->post( 'product_price_from' , TRUE );
		 $product_price_to = $this->input->post( 'product_price_to' , TRUE );

		 //获取服务相关的关键字
		 $product_class_cond = $this->input->post( 'product_class_cond' , TRUE );
		 $product_class_cond_value = $this->input->post( 'product_class_cond_value' , TRUE );
		  
		 //获取交易相关的信息
		 $order_cond = $this->input->post( 'order_cond' , TRUE );
		 $order_cond_value = $this->input->post( 'order_cond_value' , TRUE );
		 $sum_price_from = $this->input->post( 'sum_price_from' , TRUE );
		 $sum_price_to = $this->input->post( 'sum_price_to' , TRUE );
		 $quantity_from = $this->input->post( 'quantity_from' , TRUE );
		 $quantity_to = $this->input->post( 'quantity_to' , TRUE );

		 //以服务为条件查询
		 //只可能有唯一的结果 结果不唯一便为异常情况
		 if( !empty( $product_class_cond_value ) ){
			 $this->db->where( $product_class_cond , $product_class_cond_value );
			 $q = $this->db->get( 'product_class' );
			 $num_result = $q->num_rows();
			 if( $num_result == 1 ){ 
				 $res = $q->row_array();
				 $product_class_cond_wherein = array( $res['class_id'] );
			 }elseif( $num_result != 0 ){
				 throw new Exception( '服务数据异常' );
			 }
		 }

		 //以商品为条件查询
		 $is_set_product_cond = FALSE;
		 if( !empty( $product_cond_value ) ){
			 $is_set_product_cond = TRUE;
			 $this->db->where( $product_cond , $product_cond_value );
		 }
		 if( !empty( $product_price_from ) ){
			 $is_set_product_cond = TRUE;
			 $this->db->where( 'price >=' , $product_price_from );
		 } 
		 if( !empty( $product_price_to ) ){
			 $is_set_product_cond = TRUE;
			 $this->db->where( 'price <=' , $product_price_to );
		 }
		 if( $is_set_product_cond ){
			 $q = $this->db->get( 'product' );
			 if( $q->num_rows() > 0 ){
				 $res = $q->result_array();
				 foreach( $res as $index=>$item ){
					 $product_cond_wherein[] = $item['product_id'];
				 }
			 }else{
				 //对于不存在的商品
				 $product_cond_wherein[] = 'NIL'; 
			 }
		 }
		 //以交易为条件查询
		 $is_set_order_cond = FALSE;
		 if( !empty( $order_cond_value ) || $order_cond == 'address' ){	
			 //如果查询的条件为 address 则
			 if( $order_cond == 'address' ){
				 $order_cond_address['loc_province'] = $this->input->post( 'loc_province' , TRUE );
				 $order_cond_address['loc_city'] = $this->input->post( 'loc_city' , TRUE );
				 $order_cond_address['loc_town'] = $this->input->post( 'loc_town' , TRUE );
				 $order_cond_address['address_detail'] = $this->input->post( 'address_detail' , TRUE );
				 $order_cond_address['zip'] = $this->input->post( 'zip' , TRUE ); 
				 $order_cond_address['name'] = $this->input->post( 'name' , TRUE );
				 $order_cond_address['tel'] = $this->input->post( 'tel' , TRUE ); 
				 //因为在数据库中所有的地址信息是放在一起进行存放的 因此
				 $make_like_cond = function() use ( $order_cond_address ) {
					 foreach( $order_cond_address as $key=>$value ){
						 if( !empty( $value ) ){
							 switch( $key ){
							 case 'zip':
								 $like_cond[] = "邮编:%$value%";
								 break;	 
							 case 'tel':
								 $like_cond[] = "联系电话:%$value%";
								 break;
							 case 'name':
								 $like_cond[] = "收件人:%$value%";
								 break;
							 default:
								 $like_cond[] = "%$value%";
							 }
						 }else{
							 $like_cond[] = "%";
						 }
					 }	 
					 return $like_cond;
				 };
				 $like_cond = join( ', ' , $make_like_cond() );
				 $this->db->where( 'address LIKE' , $like_cond );
			 }else{
				 $this->db->where( $order_cond , $order_cond_value );
			 }
		 }
		 if( !empty( $sum_price_from ) ){
			 $is_set_order_cond = TRUE;
			 $this->db->where( 'sum_price >=' , $sum_price_from );
		 } 
		 if( !empty( $sum_price_to ) ){
			 $is_set_order_cond = TRUE;
			 $this->db->where( 'sum_price <=' , $sum_price_to );
		 }
		 if( !empty( $quantity_from ) ){
			 $is_set_order_cond = TRUE;
			 $this->db->where( 'quantity >=' , $quantity_from );
		 } 
                if( !empty( $quantity_to ) ){
                        $is_set_order_cond = TRUE;
                        $this->db->where( 'quantity <=' , $quantity_to );
                }
                if( !empty( $order_time_from ) ){
                        $this->db->where( 'time >=' , strftime( "%Y-%m-%d" , strtotime( $order_time_from ) ) );
                } 
                if( !empty( $order_time_to ) ){
                        $this->db->where( 'time <=' , strftime( "%Y-%m-%d" , strtotime( $order_time_to ) ) );
                }
                //综合各个条件
                if( !empty( $product_cond_wherein ) ){
                        $this->db->where_in( 'product_id' , $product_cond_wherein );
                }
                if( !empty( $product_class_cond_wherein ) ){
                        $this->db->where_in( 'product_class_id' , $product_class_cond_wherein );
                }
                $this->db->order_by( 'time' , 'DESC' );
                $q = $this->db->get( 'order' );
                $search_sql = $this->db->last_query();
	 	//将这条已经缓存了的sql语句传递给
                //order/show
                $this->session->set_userdata( 'search_sql' , $search_sql );
                $this->session->set_userdata( 'count_search_result' , $q->num_rows() );
                header( 'Location: /admin/order/show/search/' );
                exit;
        }/*}}}*/

        //删除一条订单信息
        public function ajax_do_delete_order(){
                $order_sn = $this->input->post( 'order_sn' , TRUE );
                //@todo 检测 $order_id 的有效性
                $this->load->model( 'order_model' , '' , TRUE );
                try{
                        $this->order_model->del( array( 'order_sn'=>$order_sn ) );
                        echo '{"res":"TRUE"}';
                }catch( Exception $e ){
                        echo '{"res":"FALSE"}';
                        handle_exception( $e , TRUE );
                }
        }

        //修改一条订单信息
        public function ajax_do_update_order(){
                $order_sn = $this->input->post( 'order_sn' , TRUE );
                //$product_id = $this->input->post( 'product_id' , TRUE );
                //$user_id = $this->input->post( 'user_id' , TRUE );
                //$product_class_id = $this->input->post( 'product_class_id' , TRUE );
                $sum_price = $this->input->post( 'sum_price' , TRUE );
                $quantity = $this->input->post( 'quantity' , TRUE );
                $status = $this->input->post( 'status' , TRUE );
                $time = $this->input->post( 'time' , TRUE );
                $address = $this->input->post( 'address' , TRUE );

                $this->load->model( 'order_model' , '' , TRUE );
                try{
                        $this->order_model->update( 
                                array( 
                                        //'product_id'=>$product_id ,  
                                        //'user_id'=>$user_id ,
                                        //'product_class_id'=>$product_class_id ,
                                        'sum_price'=>$sum_price ,
                                        'quantity'=>$quantity ,
                                        'status'=>$status ,
                                        'time'=>$time ,
                                        'address'=>$address
                                ) , 
                                array( 'order_sn'=>$order_sn ) );
                        echo '{"res":"TRUE"}';
                }catch( Exception $e ){
                        echo '{"res":"FALSE"}';
                        handle_exception( $e , TRUE );
                }
        }
        /*}}}*/

//商品管理
/*{{{*/
	public function product(){
	/*{{{*/
		$action = $this->uri->segment( 3 );
		switch( $action ){
			case 'show':
				$this->product_show();
				break;
			case 'add':
				$this->add_new_product();
				break;
			case 'do_add':
				$this->do_add_new_product();
				break;
			case 'search':
				$this->product_search();
				break;
                        case 'do_search_product_at_spec_class':
                                $_POST['force_search_with_product_class'] = TRUE;
				$this->do_product_search();
                                break;
                        case 'do_search_product':
				$this->do_product_search();
                                break;
                        case 'del':
				$this->ajax_do_del_product();
				break;
			default:
				$this->product_show();
				break;
		} 
	}/*}}}*/ 

	public function ajax_do_del_product(){
	/*{{{*/
                if( !$this->check_priv( 'SUPER' ) ){
                        echo json_encode( array( 'check_priv'=>'FALSE' , 'res'=>'FALSE' ) );
                        return;
                }
		$product_id = $this->input->post( 'product_id' , TRUE );
                $this->load->model( 'product_model' , '' , TRUE );
                $this->load->model( 'product_at_spec_class_model' , '' , TRUE );
                try{
                        //删除商品的同时 需要删除该商品在特殊服务中的相应记录
			$this->product_model->del( array( 'product_id'=>$product_id ) );
                        $this->product_at_spec_class_model->del_all_by_product_id( $product_id  );
		}catch( Exception $e ){
			return '{"res":"FALSE"}';
			handle_exception( $e , TRUE );
		}
		echo '{"res":"TRUE"}';
	}/*}}}*/

	//获得商品所属的服务信息
	public function ajax_get_product_at_spec_class_info(){
	/*{{{*/
		//获得商品id
		$product_id = $this->input->get( 'product_id' , TRUE );
		$this->load->model( 'product_at_spec_class_model' , '' , TRUE );
		try{
			$product_at_spec_class = $this->product_at_spec_class_model->find_all_with_spec_class_info( array( 'product_id'=>$product_id ) );
		 	echo json_encode( $product_at_spec_class );
		}catch( Exception $e ){
			echo '{"res":"FALSE"}';
			handle_exception( $e , TRUE );
		}
	}/*}}}*/

	//删除商品和某一个服务的关系 
	public function ajax_do_del_product_at_spec_class(){
	/*{{{*/
                if( !$this->check_priv( 'SUPER' ) ){
                        echo json_encode( array( 'check_priv'=>'FALSE' , 'res'=>'FALSE' ) );
                        return;
                }
		//获得 product_id 以及 product_class_id 
		$product_id = $this->input->post( 'product_id' );
		$product_class_id = $this->input->post( 'product_class_id' );
		$this->load->model( 'product_at_spec_class_model' , '' , TRUE );
		$cond = array( 'product_id'=>$product_id , 'product_class_id'=>$product_class_id );
		try{
			$this->product_at_spec_class_model->del( $cond );
			//删除成功
			//获得余量
                        $remain = $this->product_at_spec_class_model->find_all( array( 'product_id'=>$product_id ) );
			$res = array( 'res'=>'TRUE' , 'remain'=>count( $remain ) );
			echo json_encode( $res );
		}catch( Exception $e ){
			log_message( 'error' , $e->getMessage() );
			echo '{"res":"FALSE"}';	
		};
	}/*}}}*/

	//对于某一个商品获取当前可以关联的服务的列表
	public function ajax_get_avilable_product_class_list(){
	/*{{{*/
		$product_id = $this->input->get( 'product_id' , TRUE );
		$this->load->model( 'product_at_spec_class_model' , '' , TRUE );
		$already_connect_prodcut_class_list = $this->product_at_spec_class_model->find_all( array( 'product_id'=>$product_id ) );
		//获得所有的服务种类
		$this->load->model( 'product_class_model' , '' , TRUE );
		$all_product_class_list = $this->product_class_model->find_all();
		//@todo 可以优化 
		//判断还没有关联的服务种类
		$avilable_product_class_list = array();
		foreach( $all_product_class_list as $no=>$product_class_info ){
			 $avilable_product_class_list[$no] = $product_class_info; 
		}

		foreach( $avilable_product_class_list as $index=>$product_class ){
			foreach( $already_connect_prodcut_class_list as $no=>$already_connect_prodcut_class ){
				if( $already_connect_prodcut_class['product_class_id'] == $product_class['class_id'] ){
					 unset( $avilable_product_class_list[$index] );
				}
			}
		}

		foreach( $already_connect_prodcut_class_list as $index=>$already_connect_prodcut_class ){
			foreach( $avilable_product_class_list as $no=>$product_class ){
				if( $already_connect_prodcut_class['product_class_id'] == $product_class['class_id'] ){
					 unset( $avilable_product_class_list[$index] );
				}
			}
		}
		
		echo json_encode( $avilable_product_class_list );
	}/*}}}*/

	//将一个商品关联到一个服务上去
	public function ajax_do_add_new_product_at_spec_class(){
        /*{{{*/
                if( !$this->check_priv( 'SUPER' ) ){
                        echo json_encode( array( 'check_priv'=>'FALSE' , 'res'=>'FALSE' ) );
                        return;
                }
		$product_id = $this->input->post( 'product_id' , TRUE );
		$product_class_id = $this->input->post( 'product_class_id' , TRUE );
		//得到可能覆盖的原商品信息
		$title = $this->input->post( 'title' , TRUE );
		$describe = $this->input->post( 'describe' , TRUE );
		$price = $this->input->post( 'price' , TRUE );
		$this->load->model( 'product_at_spec_class_model' , '' , TRUE );
		try{
			$this->product_at_spec_class_model->add_new(
			 	array( 'product_id'=>$product_id , 'product_class_id'=>$product_class_id , 'title'=>$title ,
				'describe'=>$describe , 'price'=>$price ) );
			echo '{"res":"TRUE"}';			
		}catch( Exception $e ){
			echo '{"res":"FALSE"}';
			handle_exception( $e , TRUE );
		}
	}/*}}}*/

	//更新 product 信息
        public function ajax_do_edit_product(){
        /*{{{*/
                if( !$this->check_priv( 'SUPER' ) ){
                        echo json_encode( array( 'check_priv'=>'FALSE' , 'res'=>'FALSE' ) );
                        return;
                }
		$product_id = $this->input->post( 'product_id' , TRUE );
		$title = $this->input->post( 'title' , TRUE );
		$describe = $this->input->post( 'describe' , TRUE );
		$price = $this->input->post( 'price' , TRUE );
		$this->load->model( 'product_model' , '' , TRUE );
		try{
			$this->product_model->update(
				array( 'title'=>$title , 'describe'=>$describe , 'price'=>$price ) ,
				array( 'product_id'=>$product_id ) );
			echo '{"res":"TRUE"}';			
		}catch( Exception $e ){
			echo '{"res":"FALSE"}';
			handle_exception( $e , TRUE );
		}
	}/*}}}*/

	//更新 product_at_spec_class 信息
        public function ajax_do_edit_product_at_spec_class(){
        /*{{{*/
                if( !$this->check_priv( 'SUPER' ) ){
                        echo json_encode( array( 'check_priv'=>'FALSE' , 'res'=>'FALSE' ) );
                        return;
                }
		$product_id = $this->input->post( 'product_id' , TRUE );
		$product_class_id = $this->input->post( 'product_class_id' , TRUE );
		//得到可能覆盖的原商品信息
		$title = $this->input->post( 'title' , TRUE );
		$describe = $this->input->post( 'describe' , TRUE );
		$price = $this->input->post( 'price' , TRUE );
		$this->load->model( 'product_at_spec_class_model' , '' , TRUE );
		try{
			$this->product_at_spec_class_model->update(
				array( 'title'=>$title , 'describe'=>$describe , 'price'=>$price ) ,
				array( 'product_id'=>$product_id , 'product_class_id'=>$product_class_id ) );
			echo '{"res":"TRUE"}';			
		}catch( Exception $e ){
			echo '{"res":"FALSE"}';
			handle_exception( $e , TRUE );	
		}	 
	}/*}}}*/

	//获得商品的原始信息
	public function ajax_get_product_ori_info(){
	/*{{{*/
		$product_id = $this->input->get( 'product_id' , TRUE );
		$this->load->model( 'product_model' , '' , TRUE );
		try{
			$product_ori_info = $this->product_model->find( array( 'product_id'=>$product_id ) );
			$product_ori_info['res'] = "TRUE"; 
			echo json_encode( $product_ori_info );
		}catch( Exception $e ){
			echo $e->getMessage();
		}
	}/*}}}*/

	//判断某商品是否还能关联到
	//其他服务上
	private function can_add_new_class( $product_id = '' ){
	/*{{{*/
		$this->load->model( 'product_at_spec_class_model' , '' , TRUE );
		$this->load->model( 'product_class_model' , '' , TRUE );

		//当前系统中存在的服务种类个数
		$classes = $this->product_class_model->find_all();
		$classes_count = count( $classes );

		//当前商品已经关联
		//的服务的个数
		$product_at_spec_class_info = $this->product_at_spec_class_model->find_all( array( 'product_id'=>$product_id ) );
		$product_at_spec_class_count = count( $product_at_spec_class_info );

		if( $product_at_spec_class_count < $classes ){
			 return TRUE;
		}else{
			 return FALSE;
		}
	}/*}}}*/

	//显示已有的商品信息
	private function product_show(){
	/*{{{*/
		$this->load->library('pagination');
		$this->config->load('pagination');
		$this->load->model( 'product_model' , '' , TRUE );
		$this->load->model( 'product_class_model' , '' , TRUE );
		
		$cond = $this->uri->segment( 4 );
		if( $cond != 'search' ){
                        $this->session->unset_userdata( 'search_sql' );
                        $this->session->unset_userdata( 'search_by_product_at_spec_class_name_cn' );
		}
                $search_sql = $this->session->userdata( 'search_sql' );
		$config = $this->config->item( 'pagination' );
		$per_page = empty( $offset ) ? INFINITY : $config['per_page'];
		$config['base_url'] = "/admin/product/show/$cond?";	 
       	        $offset = $this->input->get( 'pager' , TRUE );
		if( empty( $offset ) ){
			$offset = 0;
		}	
                //如果设置了 product_class 的条件则
		if( stristr( $search_sql , 'product_at_spec_class' ) ){
			$this->load->model( 'product_at_spec_class_model' , '' , TRUE );
			$products = $this->product_at_spec_class_model->find_all(
			 	'' ,
			 	array( 'title'=>'product_id' , 'order'=>'DESC' ) ,
			 	$per_page , 
			 	$offset,
			 	$search_sql
			);
                        $mod = 'product_show_spec';
		}else{
			$products = $this->product_model->find_all(
				'' ,
				array( 'title'=>'product_id' , 'order'=>'DESC' ) ,
				$per_page , 
				$offset,
				$search_sql
			);
			$mod = 'product_show'; 
		}
		$config['total_rows'] = count( $products );
		$this->pagination->initialize( $config );
		$pager_links = $this->pagination->create_links();
		$res = $this->session->flashdata( 'res' );
		//循环判断每一个商品是否有
                //再和其他服务关联的可能性
                //以及获取服务名称
		foreach( $products as $no=>$info ){
                        $products[$no]['can_add_new_class'] = $this->can_add_new_class( $info['product_id'] );
                        if( $mod == 'product_show_spec' ){
                                $products[$no]['product_class_name_cn'] = $this->product_class_model->get_class_name_by_id( $info['product_class_id'] );
                        }
 		}
		$this->load->view( 'admin/template_page' , 
			array( 'mod'=>$mod , 'nav_active'=>'product_admin' , 'sub_active'=>'show' , 'product_infos'=>$products , 'res'=>$res , 'pager_links'=>$pager_links , 'item_count'=>$config['total_rows'] , 'admin'=>$this->admin ) );	 
	}/*}}}*/

	//添加新的商品
	private function add_new_product(){
	/*{{{*/
		$res = $this->session->flashdata( 'res' );
		$this->load->view( 'admin/template_page' , 
			array( 'mod'=>'add_new_product' , 'nav_active'=>'product_admin' , 'sub_active'=>'add' , 'res'=>$res , 'admin'=>$this->admin ) );	 
	}/*}}}*/

	private function do_add_new_product(){
	/*{{{*/
                if( !$this->check_priv( 'SUPER' ) ){
			$this->session->set_flashdata( 'res' , array( 'info'=>'您的权限无法进行此项操作') );
			header( 'location: /admin/product/add/' );
			exit;
                }
		$title = $this->input->post( 'title' , TRUE );
		$describe = $this->input->post( 'describe' , TRUE );
		$price = $this->input->post( 'price' , TRUE );
		$title_len = strlen( $title );
		$describe_len = strlen( $describe );
		//判断新添加的商品的信息的有效性
		if( !( !empty( $title ) && !empty( $describe ) && !empty( $price ) && is_numeric( $price ) && ($title_len <= 128) && ($describe_len <= 2046) ) ){
			$this->session->set_flashdata( 'res' , array( 'info'=>'填写的商品信息格式不正确，请注意上方的提示信息' , 'type'=>'error' ) );		
			header( 'location: /admin/add_new_product/' );
			exit;
		}
		$this->load->model( 'product_model' , '' , TRUE );
		try{
			$this->product_model->add_new( array( 'title'=>$title , 'describe'=>$describe , 'price'=>$price ) );
			//添加成功 跳转到列表页面
			$this->session->set_flashdata( 'res' , array( 'info'=>'添加新的商品成功' ) );
			header( 'location: /admin/product/show/' );
			exit;
		}catch( Exception $e ){
			show_error( $e->getMessage() );	
		}
	}/*}}}*/

	private function product_search(){
	/*{{{*/
                $res = $this->session->flashdata( 'res' );
		$this->load->view( 'admin/template_page' ,
			array( 'mod'=>'product_search' , 'nav_active'=>'product_admin' , 'sub_active'=>'search' , 'res'=>$res , 'admin'=>$this->admin ) );
	}/*}}}*/

	private function do_product_search(){
	/*{{{*/
                if( !$this->check_priv( 'SUPER' ) ){
                        $this->session->set_flashdata( 'res' , array( 'info'=>"您的权限无法进行此项操作" ) );
                        header( 'Location: /admin/product/search' );
                        exit;
                }
		//如果设置了product_class的条件则从product_at_spec_class表中查找相应的信息
		//目前只提供按照服务名称查找的功能
		$product_class_cond =$this->input->post( 'product_class_cond' , TRUE );
                $product_class_cond_value =$this->input->post( 'product_class_cond_value' , TRUE );
                $force_search_with_product_class = $this->input->post( 'force_search_with_product_class' , TRUE );
                if( !empty( $force_search_with_product_class ) ){
                         $search_from = 'product_at_spec_class';
                }
		if( !empty( $product_class_cond_value ) ){
			//转换 product_class_name_cn 到 product_class_id
			//@todo 目前只能根据 class_name_cn 进行查询
                        $this->load->model( 'product_class_model' , '' , TRUE );
			$product_class_id = $this->product_class_model->get_class_id_by_name_cn( $product_class_cond_value );
                        $this->db->where( 'product_class_id' , $product_class_id );
                        //设置从 product_at_spec_class 表中查找
                        $search_from = 'product_at_spec_class';
                }  
                //按照方案发布的时间进行查询
                $product_time_from = $this->input->post( 'product_time_from' , TRUE );
                $product_time_to = $this->input->post( 'product_time_to' , TRUE );
                if( !empty( $product_time_from ) ){
                        $this->db->where( 'time >=' , strftime( "%Y-%m-%d" , strtotime( $product_time_from ) ) );
                }
                if( !empty( $product_time_to ) ){
                        $this->db->where( 'time <=' , strftime( "%Y-%m-%d" , strtotime( $product_time_to ) ) );
                }
                //按照方案的其他关键字进行搜索
                $product_cond = $this->input->post( 'product_cond' , TRUE );
                $product_cond_value = $this->input->post( 'product_cond_value' , TRUE );
                if( !empty( $product_cond_value ) ){
                        $this->db->where( $product_cond , $product_cond_value );
                }
                //按照价格范围进行查找
                $product_price_from = $this->input->post( 'product_price_from' , TRUE );
                $product_price_to = $this->input->post( 'product_price_to' , TRUE );
                if( !empty( $product_price_from ) ){
                        $this->db->where( 'price >=' , $product_price_from  );
                }
                if( !empty( $product_price_to ) ){
                        $this->db->where( 'price <=' , $product_price_to );
                }
                $search_from = !empty( $search_from ) ? $search_from : 'product';
                $q = $this->db->get( $search_from );
		$search_sql = $this->db->last_query();
		//显示结果
		$this->session->set_userdata( 'search_sql' , $search_sql );
		header( 'Location: /admin/product/show/search/' );
		exit;
		
		//按照服务的关键字进行搜索 如果提供了服务的关键字则在结果页面会只显示
		//某商品在特殊的服务上的信息
	}/*}}}*/
/*}}}*/

//权限管理/
/*{{{*/
	 public function priv(){
		 $action = $this->uri->segment( 3 );
		 switch( $action ){
			 case 'show':
				 $this->priv_show();
				 break;
			 case 'add':
				 $this->priv_add_new();
				 break;
			 default:
				 $this->priv_show();
				 break;	  
		 }
	 }
	
	 //显示所有的管理员列表	 
	 private function priv_show(){
		 $this->load->model( 'admin_model' , '' , TRUE );
		 $admins = $this->admin_model->find_all();

		 $this->load->view( 'admin/template_page' , 
			array( 'mod'=>'admin_show' , 'nav_active'=>'priv_admin' , 'sub_active'=>'show' , 'admins'=>$admins , 'admin'=>$this->admin ) );	 
	 }

	 //添加新的管理员
         private function priv_add_new(){
                 $res = $this->session->flashdata( 'res' );
		 $this->load->view( 'admin/template_page' ,
			array( 'mod'=>'admin_add_new' , 'nav_active'=>'priv_admin' , 'sub_active'=>'add' , 'res'=>$res , 'admin'=>$this->admin ) );	 
	 }

         public function priv_do_add_new_admin(){
                if( !$this->check_priv( 'SUPER' ) ){
                        $this->session->set_flashdata( 'res' , array( 'info'=>'您的权限无法进行此项操作' ) );
                        header( 'location: /admin/priv/add/' );
                        exit;
                }
                $admin = $this->input->post( 'admin' , TRUE );
                $password = $this->input->post( 'password' , TRUE );
                $priv = $this->input->post( 'priv' , TRUE );

                $this->load->model( 'admin_model' , '' , TRUE );
                $admin_info = $this->admin_model->find( array( 'admin'=>$admin ) );
                if( !empty( $admin_info ) ){
                        //系统中已经存在同名管理员
                        $this->session->set_flashdata( 'res' , array( 'info'=>'系统中已经存在该管理员帐号' ) );
                        header( 'location: /admin/priv/add/' );
                        exit;
                }
                $this->admin_model->add_new( array( 'admin'=>$admin , 'password'=>md5( $password ) , 'priv'=>$priv ) );
                header( 'location: /admin/priv/' );
                exit;
         }

         public function ajax_priv_do_del(){
                if( !$this->check_priv( 'SUPER' ) ){
                        echo json_encode( array( 'check_priv'=>'FALSE' , 'res'=>'FALSE' ) );
                        return;
                }
                $admin_id = $this->input->post( 'admin_id' , TRUE );
                if( empty( $admin_id ) ){
                        echo '{"res":"FALSE"}'; 
                        return;
                }
                $this->load->model( 'admin_model' , '' , TRUE );
                try{
                        $this->admin_model->del( array( 'admin_id'=>$admin_id ) ); 
                        echo '{"res":"TRUE"}'; 
                }catch( Exception $e ){
                        echo '{"res":"FALSE"}';
                        handle_exception( $e , TRUE );
                }
         }

         public function ajax_priv_do_update(){
                 if( !$this->check_priv( 'SUPER' ) ){
                         echo json_encode( array( 'check_priv'=>'FALSE' , 'res'=>'FALSE' ) );
                         return;
                 }
                 $admin_id = $this->input->post( 'admin_id' , TRUE );
                 $admin = $this->input->post( 'admin' , TRUE );
                 $priv = $this->input->post( 'priv' , TRUE );
                 $password = $this->input->post( 'password' , TRUE );
                 $this->load->model( 'admin_model' , '' , TRUE );
                 try{
                         $this->admin_model->update( array( 'admin'=>$admin , 'priv'=>$priv ) , array( 'admin_id'=>$admin_id ) );
                         if( !empty( $password ) ){
                                 $this->admin_model->update( array( 'password'=>md5( $password ) ) , array( 'admin_id'=>$admin_id ) );
                         }
                         echo '{"res":"TRUE"}'; 
                 }catch( Exception $e ){
                         echo '{"res":"FALSE"}'; 
                         handle_exception( $e , TRUE );
                 }
         }
         /*}}}*/
}
